import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')
  const userInfo = ref(null)
  const permissions = ref([])

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.username || '')
  const displayName = computed(() => userInfo.value?.display_name || userInfo.value?.username || '')
  const userRole = computed(() => userInfo.value?.role_name || '')
  const roleId = computed(() => userInfo.value?.role_id || 0)
  const isSuperUser = computed(() => userInfo.value?.is_superuser || false)
  const department = computed(() => userInfo.value?.department || '')
  const position = computed(() => userInfo.value?.position || '')

  // 登录
  const login = async (credentials) => {
    try {
      const response = await loginApi(credentials)

      if (response.success) {
        // 保存token
        token.value = response.data.access_token
        refreshToken.value = response.data.refresh_token
        localStorage.setItem('token', response.data.access_token)
        localStorage.setItem('refreshToken', response.data.refresh_token)

        // 保存用户信息
        userInfo.value = response.data.user

        // 登录成功后获取完整的用户信息（包括头像等）
        try {
          await getUserInfo()
        } catch (error) {
          console.warn('获取完整用户信息失败，使用登录返回的基础信息:', error)
        }

        return { success: true, data: response.data }
      } else {
        return {
          success: false,
          message: response.message || '登录失败'
        }
      }
    } catch (error) {
      console.error('登录失败:', error)

      // 处理不同类型的错误
      if (error.response) {
        const errorData = error.response.data
        return {
          success: false,
          message: errorData.message || '登录失败，请重试'
        }
      } else if (error.request) {
        return {
          success: false,
          message: '网络连接失败，请检查网络'
        }
      } else {
        return {
          success: false,
          message: '登录失败，请重试'
        }
      }
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await getUserInfoApi()
      if (response.success) {
        userInfo.value = response.data
        return response.data
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能token已过期，执行登出
      logout()
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 调用后端登出API
      if (token.value) {
        await logoutApi({ refresh_token: refreshToken.value })
      }
    } catch (error) {
      console.error('登出API调用失败:', error)
      // 即使API调用失败，也要清除本地数据
    } finally {
      // 清除本地数据
      token.value = ''
      refreshToken.value = ''
      userInfo.value = null
      permissions.value = []
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    }
  }

  // 更新用户头像
  const updateAvatar = (avatarUrl) => {
    if (userInfo.value) {
      userInfo.value.avatar_url = avatarUrl
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }

  return {
    // 状态
    token,
    refreshToken,
    userInfo,
    permissions,

    // 计算属性
    isAuthenticated,
    userName,
    displayName,
    userRole,
    roleId,
    isSuperUser,
    department,
    position,

    // 方法
    login,
    logout,
    getUserInfo,
    updateAvatar,
    hasPermission
  }
})
